package crazyboyfeng.autodroid.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Environment;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import crazyboyfeng.autodroid.R;
import crazyboyfeng.autodroid.bean.TaskBean;
import crazyboyfeng.autodroid.tasks.TaskManager;
import crazyboyfeng.autodroid.tools.FixedMultiSelectListPreference;
import crazyboyfeng.autodroid.utils.WeekTools;

public class AddNewTaskActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	private int mYear;
	private int mMonth;
	private int mDay;

	private int mHour;
	private int mMinute;
	private TaskManager mTM = new TaskManager();

	private TaskBean taskBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		init();
		super.onCreate(savedInstanceState);
		this.getActionBar().setDisplayShowHomeEnabled(true);
		this.getActionBar().setDisplayHomeAsUpEnabled(true);
		// Load the preferences from an XML resource
		this.addPreferencesFromResource(R.xml.task_preference);
		setContentView(R.layout.add_main);
		this.initSummaries(this.getPreferenceScreen());
		this.getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(this);
	}

	public void init() {
		TaskBean task = mTM.getTaskById(this.getIntent().getStringExtra(
				"taskId"));
		if (task.getName() != null) {
			initPreference(task);
			this.taskBean = task;
			initDateTime();
		}
	}

	private void initDateTime() {
		if (taskBean.getTime().length() > 0) {
			String[] time = taskBean.getTime().split(":");
			mHour = Integer.parseInt(time[0]);
			mMinute = Integer.parseInt(time[1]);
		} else {
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			mHour = c.get(Calendar.HOUR_OF_DAY);
			mMinute = c.get(Calendar.MINUTE);
		}
	}

	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		String key = preference.getKey();
		if (key != null) {
			// if(key.equals("date_key")) {
			// showDialog(0);
			// }
			if (key.equals("time_key")) {
				showDialog(1);
			}
		}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case 1:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					false);
		}

		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			updateDisplay("date_key", mYear + "-" + mMonth + "-" + mDay);
		}
	};
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			String sHour = "" + mHour;
			if (mHour < 10)
				sHour = "0" + mHour;
			mMinute = minute;
			String sMinute = mMinute + "";
			if (mMinute < 10)
				sMinute = "0" + mMinute;
			updateDisplay("time_key", sHour + ":" + sMinute);
		}
	};

	private void updateDisplay(String key, String msg) {
		Preference p = this.findPreference(key);
		p.setSummary(msg);
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor prefsEditor = myPrefs.edit();
		prefsEditor.putString(key, msg);
		prefsEditor.commit();
	}

	private String getShardPreferencesKeyValue(String key) {
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		return myPrefs.getString(key, "");
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Preference pref = this.findPreference(key);
		setSummary(pref);
	}

	private String listToString(Set<String> cs) {
		Log.i("set", cs.toString());
		String[] list = cs.toArray(new String[0]);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < list.length; i++) {
			sb.append(" " + list[i]);
		}
		return sb.toString();
	}

	/**
	 * Set the summaries of all preferences
	 */
	private void initSummaries(PreferenceGroup pg) {
		for (int i = 0; i < pg.getPreferenceCount(); ++i) {
			Preference p = pg.getPreference(i);
			if (p instanceof PreferenceGroup)
				this.initSummaries((PreferenceGroup) p); // recursion
			else
				this.setSummary(p);
		}
	}

	/**
	 * Set the summaries of the given preference
	 */
	private void setSummary(Preference pref) {
		// react on type or key
		if (pref instanceof ListPreference) {
			ListPreference listPref = (ListPreference) pref;
			pref.setSummary(listPref.getEntry());
		} else if (pref instanceof FixedMultiSelectListPreference) {
			FixedMultiSelectListPreference msPref = (FixedMultiSelectListPreference) pref;
			pref.setSummary(WeekTools.getWeekMsg(msPref.getValues()));
		} else if (pref instanceof EditTextPreference) {
			EditTextPreference et = (EditTextPreference) pref;
			pref.setSummary(et.getText());
		} else if (pref instanceof Preference) {
			pref.setSummary(getShardPreferencesKeyValue(pref.getKey()));
		}
	}

	public void onClickSave(View v) {
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		if (checkValue(myPrefs)) {
			TaskBean tb = new TaskBean();

			tb.setName(myPrefs.getString("name_key", ""));
			tb.setTime(myPrefs.getString("time_key", ""));
			tb.setType(listToString(myPrefs.getStringSet("type_key",
					new HashSet<String>())));
			tb.setTask(myPrefs.getString("task_key", ""));
			tb.setState(myPrefs.getString("state_key", ""));

			mTM.editTask(taskBean, tb);
			mTM.resetTaskAlarm(taskBean);

			this.finish();
			overridePendingTransition(R.anim.slide_in_down,
					R.anim.slide_out_down);
		}
	}

	private boolean checkValue(SharedPreferences myPrefs) {
		if (myPrefs.getString("name_key", "").equals("")) {
			Toast.makeText(this, "请填写任务名称！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (myPrefs.getString("time_key", "").equals("")) {
			Toast.makeText(this, "请选择启动时间！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (listToString(
				myPrefs.getStringSet("type_key", new HashSet<String>()))
				.equals("")) {
			Toast.makeText(this, "请选择循环方式！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (myPrefs.getString("task_key", "").equals("")) {
			Toast.makeText(this, "请选择触发类型！", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

	public void initPreference(TaskBean task) {
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		Editor editor = myPrefs.edit();
		editor.putString("name_key", task.getName());
		// editor.putString("date_key", task.getDate());
		editor.putString("time_key", task.getTime());
		editor.putString("task_key", task.getTask());
		editor.putString("state_key", task.getState());
		Set<String> a = new HashSet<String>();
		if (task.getType() != null) {
			String[] b = task.getType().split(" ");
			for (int i = 0; i < b.length; i++) {
				a.add(b[i]);
			}
		}
		editor.putStringSet("type_key", a);
		editor.commit();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			overridePendingTransition(R.anim.slide_in_down,
					R.anim.slide_out_down);
			return true;
		case R.id.menu_del:
			deleteTask();
			return true;
		case R.id.menu_share:
			saveTask(1);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void saveTask(int number) {
		try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File saveFile = new File(Environment.getExternalStorageDirectory().getCanonicalPath()+ "/Autodroid/"+number+".task");
                if (!saveFile.exists()) {
                	saveFile.getParentFile().mkdirs();
                	saveFile.createNewFile();
    				doSave(saveFile);
    				Toast.makeText(getApplicationContext(), "成功保存到"+saveFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
    			} else {
    				saveTask(number + 1);
    			}
            }else{
            	Toast.makeText(getApplicationContext(), "没有检测到外部存储！",Toast.LENGTH_SHORT).show();
            }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void doSave(File saveFile) {
		try {
			FileOutputStream fos = new FileOutputStream(saveFile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(taskBean);
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void deleteTask() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("确定删除 " + taskBean.getName() + " 吗？")
				.setPositiveButton("是", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						doDelete();
					}
					// 设置取消按钮
				})
				.setNegativeButton("否", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		// 创建对话框
		AlertDialog ad = builder.create();
		// 显示对话框
		ad.show();
	}

	private void doDelete() {
		mTM.deleteTask(taskBean);
		Toast.makeText(this.getApplicationContext(),
				taskBean.getName() + " 删除成功！", 1000).show();
		this.finish();
		overridePendingTransition(R.anim.slide_in_down, R.anim.slide_out_down);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menus_add, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.slide_in_down, R.anim.slide_out_down);
	}

}
